#!/usr/bin/env bash
# 读取基本信息
arg=$1 # 参数, 是否默认yes
stat=() # 仓库状态, 给默认值, 防止后续出错
stat=`git status` # 当前仓库状态
branch=`git symbolic-ref --short -q HEAD` # 当前所处分支
remote=() # 远程仓库列表, 给默认值
remote=`git remote show` # 远程仓库列表

# 做拉取代码操作
function pull_remote() {
    for ll in ${remote[@]}; do
        echo ""
        echo "Start Sync Remote : [${ll}]"
        if [[ "$arg" != *y* ]];then  # 如果未指定 -y | --yes 参数, 需要各个仓库进行询问
            echo ""
            echo "Do You Want Sync Remote : [${ll}] (y/n)"
            read result
            if [[ "$result" != n* ]];then # 用户确认拉取该仓库
                git pull ${ll} ${branch}
            fi
        else
            git pull ${ll} ${branch}
        fi
    done
}

# 当前仓库是否需要提交
for st in ${stat[@]}; do
    if [[ "$st" == "clean" ]];then
        # 不需要提交, 没有改动, 询问是否需要拉取代码
        echo "Nothing Commit !"
        echo "Do You Want Pull Remote ? (y/n)"
        read confirm
        if [[ "$confirm" != n* ]];then
            pull_remote
        fi
        exit
    fi
done

# 有改动, 读取提交说明
echo "Please Add Commit Description : (Description/exit)"
read commit_description
if [[ "$commit_description" == "exit" ]]; # 用户输入exit, 退出
then
    exit
fi
git add . &&
git commit -m "$commit_description"

# 遍历远程仓库, 做sync
for ll in ${remote[@]}; do
    echo ""
    echo "Start Sync Remote : [${ll}]"
    if [[ "$1" != *y* ]];then
        echo ""
        echo "Do You Want Sync Remote : [${ll}] (y/n)"
        read result
        if [[ "$result" != n* ]];then
            git pull ${ll} ${branch}
            git push ${ll} ${branch}
        fi
    else
        git pull ${ll} ${branch}
        git push ${ll} ${branch}
    fi
done
